package com.qf.application.controller;


import com.qf.application.entity.User;
import com.qf.application.service.OrderService;
import com.qf.application.service.UserService;
import com.qf.application.uploadimage.UploadServlet;
import com.qf.application.utils.result.Result;
import com.qf.application.utils.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author l
 * @since 2024-07-09
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private  UploadServlet uploadServlet;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @PostMapping("/save-file")
    public Result Order(MultipartFile file, HttpServletRequest request) throws IOException {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if("g_token".equals(cookie.getName())){
                    String token = cookie.getValue();
                    System.out.println("token = " + token);
                    Long userId = JwtUtils.getUserId(token);
                    User user = userService.getById(userId);
                    if(user.getCode()==1){
                        String url = uploadServlet.uploadFile(file);
                        Boolean b = orderService.saveOrder(url, new Date(),user.getId());

                        return  Result.success(b,"上传凭证成功");

                    }
                }
            }
        }
        return Result.error(330,"未激活");
    }

}
